<template>
  <div class="app-container">
    <el-form :model="modeFrom" size="small" label-width="100px">
      <el-form-item label="年检模式" prop="value">
        <el-radio-group v-model="modeFrom.value" @input="changeMode">
          <div style="margin: 10px 0">
            <el-radio label="1">
              <span>普通模式</span>
              <p>
                计算规则说明：<br />
                所有任务首先除与期数 ，得出一个最大可除数，剩余不可除数平均分配到每个月上
              </p>
            </el-radio>
          </div>
          <div>
            <el-radio label="2">
              <span>特殊</span>
              <p>
                计算规则说明：<br />
                所有任务按每月8%，季度25% 计算 ，<br />
                当计算结果不等于整数时，按应收尽收原则，<br />
                例：每月应做2.1个任务，则系统自动默认为3个任务
              </p>
            </el-radio>
          </div>
        </el-radio-group>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="setModeSetting"> 保存并实施 </el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8" v-if="currentMode == '2'">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
        >
          新增
        </el-button>
      </el-col>
    </el-row>
    <div v-if="currentMode == '2'">
      <div v-for="item in dataList" :key="item.systemId" class="table-item">
        <div class="table-title">
          {{ item.systemName || "系统名称" }}
        </div>
        <el-table :data="item.itemResultVOList" border :span-method="mergeCall">
          <el-table-column label="设备名称" align="center" prop="deviceName" />
          <el-table-column label="标准" align="center" prop="type">
            <template slot-scope="scope">
              {{ dictLabel(scope.row.type) }}
            </template>
          </el-table-column>
          <el-table-column label="频次" align="center" prop="inspectionCycle" />
          <el-table-column align="center" label="操作">
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-delete"
                @click="handleDelete(scope.row)"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
    <el-dialog
      title="新增设备"
      :visible.sync="editShow"
      width="600px"
      append-to-body
      :close-on-click-modal="false"
    >
      <el-form ref="editForm" :model="editForm" :rules="rules" label-width="80px">
        <el-form-item label="标准" prop="type">
          <el-select
            v-model="editForm.type"
            placeholder="请选择标准"
            style="width: 100%"
            filterable
            @change="changeTypeOrSystem"
          >
            <el-option
              v-for="i in dictList"
              :key="i.dictValue"
              :label="i.dictLabel"
              :value="i.dictValue"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="系统名称" prop="systemId">
          <el-select
            v-model="editForm.systemId"
            placeholder="请选择系统名称"
            style="width: 100%"
            filterable
            @change="changeTypeOrSystem"
          >
            <el-option
              v-for="i in systemList"
              :key="i.id"
              :label="i.name"
              :value="i.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="设备名称" prop="deviceId">
          <el-select
            v-model="editForm.deviceId"
            placeholder="请选择设备名称"
            style="width: 100%"
            filterable
            multiple
          >
            <el-option
              v-for="i in deviceList"
              :key="i.cycleId"
              :label="i.deviceName"
              :value="i.cycleId"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm" :loading="loading">确 定</el-button>
        <el-button @click="handleCancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listSystem,
  listByCalculation,
  calcDeviceList,
  calcDeviceAdd,
  calcDeviceDelete,
} from "@/api/device/system";
import { settingGetInfo, putSetting } from "@/api/system/ai";
import { getDicts } from "@/api/system/dict/data";

export default {
  name: "message",
  data() {
    return {
      loading: false, // 提交中
      currentMode: "1", // 当前模式
      modeFrom: {
        id: "TASK_GENERATION_MODE",
        value: "1", // 1: 普通 2: 特殊
      },
      dataList: [], // 数据列表
      editShow: false, // 编辑弹窗
      editForm: {}, // 编辑表单
      rules: {
        type: [{ required: true, message: "请选择标准", trigger: "blur" }],
        systemId: [{ required: true, message: "请选择系统", trigger: "blur" }],
        deviceId: [{ required: true, message: "请选择设备", trigger: "blur" }],
      },
      dictList: [], // 标准列表
      systemList: [], // 系统列表
      deviceList: [], // 设备列表
    };
  },
  mounted() {
    this.getModeSetting();
    this.getDicts();
  },
  methods: {
    // 获取模式配置
    getModeSetting() {
      settingGetInfo("TASK_GENERATION_MODE").then((res) => {
        this.modeFrom = res.data;
        this.currentMode = res.data.value;
        if (this.currentMode == "2") {
          this.getList();
        }
      });
    },
    // 修改模式配置
    setModeSetting() {
      putSetting(this.modeFrom).then((res) => {
        this.$modal.msgSuccess(res.msg);
        this.getModeSetting();
      });
    },
    // 获取设备列表
    getList() {
      listByCalculation().then((res) => {
        let list = res.data;
        list.forEach((i) => {
          let current = "";
          i.itemResultVOList.forEach((v, k) => {
            let cellNum = this.countField(v.deviceName, i.itemResultVOList, "deviceName");
            if (cellNum > 1 && current == "") {
              current = v.deviceName;
            } else if (cellNum > 1 && current == v.deviceName) {
              cellNum = 0;
            } else if (cellNum > 1 && current != v.deviceName) {
              current = v.deviceName;
            }
            v.cellNum = cellNum;
          });
        });
        this.dataList = list;
      });
    },
    // 统计次数
    countField(str, data, field) {
      let count = 0;
      data.forEach((i) => {
        if (typeof i[field] == typeof str && str == i[field]) {
          count++;
        }
      });
      return count;
    },
    // 合并单元格
    mergeCall({ row, column, rowIndex, columnIndex }) {
      if (columnIndex === 0) {
        return {
          rowspan: row.cellNum,
          colspan: row.cellNum == 0 ? 0 : 1,
        };
      }
    },
    // 标准列表
    getDicts() {
      getDicts("sys_check_standard").then((res) => {
        this.dictList = res.data;
      });
    },
    // 获取标准名称
    dictLabel(type) {
      let row = this.dictList.find((item) => item.dictValue == type);
      return row ? row.dictLabel : "";
    },
    // 获取系统列表
    getSystemList() {
      listSystem({
        pageNum: 1,
        pageSize: 1000,
      }).then((res) => {
        if (res.code == 200) {
          this.systemList = res.rows;
        }
      });
    },
    // 切换标准与系统
    changeTypeOrSystem() {
      this.deviceList = [];
      this.editForm.deviceId = null;
      if (this.editForm.type && this.editForm.systemId) {
        this.getDevictList();
      }
    },
    // 获取设备列表
    getDevictList() {
      calcDeviceList({
        type: this.editForm.type,
        systemId: this.editForm.systemId,
      }).then((res) => {
        this.deviceList = res.data;
      });
    },
    // 切换模式
    changeMode(val) {
      const h = this.$createElement;
      this.$msgbox({
        title: "规则变动",
        message: h("p", null, [
          h("div", null, "特别提示"),
          h("div", null, "本次改动将对所有单位合同任务进行大幅度调整 ，请慎重选择"),
        ]),
        showCancelButton: true,
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        closeOnClickModal: false,
        closeOnPressEscape: false,
        type: "warning",
        beforeClose: (action, instance, done) => {
          this.modeFrom.value = action === "confirm" ? val : val == "1" ? "2" : "1";
          done();
        },
      }).catch(() => {});
    },
    // 表单重置
    reset() {
      this.editForm = {
        id: null,
        type: null,
        systemId: null,
        deviceId: null,
      };
      this.deviceList = [];
      this.resetForm("editForm");
    },
    // 新增设备
    handleAdd() {
      this.reset();
      this.getSystemList();
      this.editShow = true;
    },
    // 关闭编辑弹窗
    handleCancel() {
      this.reset();
      this.editShow = false;
    },
    // 删除设备
    handleDelete(row) {
      this.$modal
        .confirm("是否确认删除设备【" + row.deviceName + "】吗？")
        .then(() => {
          calcDeviceDelete([row.id]).then((res) => {
            this.$modal.msgSuccess("删除成功");
            this.getList();
          });
        })
        .catch(() => {});
    },
    // 提交新增表单
    submitForm() {
      this.$refs["editForm"].validate((valid) => {
        if (valid) {
          this.loading = true;
          calcDeviceAdd(this.editForm.deviceId)
            .then((res) => {
              if (res.code == 200) {
                this.$modal.msgSuccess("操作成功");
                this.editShow = false;
                this.getList();
              }
            })
            .finally(() => {
              this.loading = false;
            });
        }
      });
    },
  },
};
</script>
<style lang="scss" scoped>
.table-item {
  margin-bottom: 20px;
  .table-title {
    font-weight: bold;
    line-height: 40px;
    &:before {
      content: "";
      display: inline-block;
      width: 4px;
      height: 15px;
      background-color: #409eff;
      margin-right: 5px;
    }
  }
}
</style>
